package cn.gp.chatclient.service;

import cn.gp.chatclient.api.user.UserApi;
import cn.gp.chatclient.api.user.req.AddFriendRequest;
import cn.gp.chatclient.api.user.req.LoginRequest;
import cn.gp.chatclient.api.user.req.RegisterRequest;
import cn.gp.chatclient.api.user.req.UpdateProfileRequest;
import cn.gp.chatclient.config.ClientConfig;
import cn.gp.chatclient.model.FriendRequestVo;
import cn.gp.chatclient.model.ResponseVo;
import cn.gp.chatclient.model.UserVo;
import lombok.extern.slf4j.Slf4j;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;

/**
 * @ClassName AuthService
 * @Description TODO
 * @Author He Guoping
 * @Date 2025/6/17 10:15
 * @Version JDK17
 */
@Slf4j
public class UserService {
    private final UserApi userApi;
    private Long currentUserId;

    public UserService() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ClientConfig.HTTP_BASE_URL)
                .addConverterFactory(JacksonConverterFactory.create())
                .build();
        this.userApi = retrofit.create(UserApi.class);
    }

    public UserService(UserApi userApi) {
        this.userApi = userApi;
    }

    public void login(String username, String password, Consumer<UserVo> onSuccess, Consumer<String> onError) {
        LoginRequest request = new LoginRequest(username, password);
        userApi.login(request).enqueue(new Callback<ResponseVo<UserVo>>() {
            @Override
            public void onResponse(Call<ResponseVo<UserVo>> call, Response<ResponseVo<UserVo>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    ResponseVo<UserVo> responseVo = response.body();
                    if (responseVo.isSuccess() && responseVo.getData() != null) {
                        UserVo user = responseVo.getData();
                        currentUserId = user.getId();
                        log.info("用户登录成功，设置currentUserId: {}", currentUserId);
                        onSuccess.accept(user);
                    } else {
                        log.error("登录失败: {}", responseVo.getMessage());
                        onError.accept(responseVo.getMessage());
                    }
                } else {
                    String errorMsg = "登录失败: " + (response.body() != null ? response.body().getMessage() : response.message());
                    log.error(errorMsg);
                    onError.accept(errorMsg);
                }
            }

            @Override
            public void onFailure(Call<ResponseVo<UserVo>> call, Throwable t) {
                String errorMsg = "登录失败: " + t.getMessage();
                log.error(errorMsg, t);
                onError.accept(errorMsg);
            }
        });
    }

    public void register(String username, String password, String nickname, Consumer<UserVo> onSuccess, Consumer<String> onError) {
        RegisterRequest request = new RegisterRequest(username, password, nickname);
        userApi.register(request).enqueue(new Callback<ResponseVo<UserVo>>() {
            @Override
            public void onResponse(Call<ResponseVo<UserVo>> call, Response<ResponseVo<UserVo>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    ResponseVo<UserVo> responseVo = response.body();
                    if (responseVo.isSuccess()) {
                        onSuccess.accept(responseVo.getData());
                    } else {
                        onError.accept(responseVo.getMessage());
                    }
                } else {
                    onError.accept("注册失败: " + (response.body() != null ? response.body().getMessage() : response.message()));
                }
            }

            @Override
            public void onFailure(Call<ResponseVo<UserVo>> call, Throwable t) {
                onError.accept("注册失败: " + t.getMessage());
            }
        });
    }

    public CompletableFuture<ResponseVo<UserVo>> updateProfile(UpdateProfileRequest request) {
        CompletableFuture<ResponseVo<UserVo>> future = new CompletableFuture<>();
        userApi.updateProfile(request).enqueue(new Callback<ResponseVo<UserVo>>() {
            @Override
            public void onResponse(Call<ResponseVo<UserVo>> call, Response<ResponseVo<UserVo>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    future.complete(response.body());
                } else {
                    future.completeExceptionally(new RuntimeException("更新个人信息失败: " + (response.body() != null ? response.body().getMessage() : response.message())));
                }
            }

            @Override
            public void onFailure(Call<ResponseVo<UserVo>> call, Throwable t) {
                future.completeExceptionally(t);
            }
        });
        return future;
    }

    public CompletableFuture<ResponseVo<List<UserVo>>> searchUsers(String keyword) {
        CompletableFuture<ResponseVo<List<UserVo>>> future = new CompletableFuture<>();
        userApi.searchUsers(keyword).enqueue(new Callback<ResponseVo<List<UserVo>>>() {
            @Override
            public void onResponse(Call<ResponseVo<List<UserVo>>> call, Response<ResponseVo<List<UserVo>>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    future.complete(response.body());
                } else {
                    future.completeExceptionally(new RuntimeException("搜索用户失败: " + 
                        (response.body() != null ? response.body().getMessage() : response.message())));
                }
            }

            @Override
            public void onFailure(Call<ResponseVo<List<UserVo>>> call, Throwable t) {
                future.completeExceptionally(t);
            }
        });
        return future;
    }

    public CompletableFuture<ResponseVo<Void>> sendFriendRequest(AddFriendRequest request) {
        if (currentUserId == null) {
            CompletableFuture<ResponseVo<Void>> future = new CompletableFuture<>();
            future.completeExceptionally(new RuntimeException("用户未登录"));
            return future;
        }

        request.setRequesterId(currentUserId);

        CompletableFuture<ResponseVo<Void>> future = new CompletableFuture<>();
        userApi.sendFriendRequest(request).enqueue(new Callback<ResponseVo<Void>>() {
            @Override
            public void onResponse(Call<ResponseVo<Void>> call, Response<ResponseVo<Void>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    future.complete(response.body());
                } else {
                    future.completeExceptionally(new RuntimeException("发送好友请求失败: " + 
                        (response.body() != null ? response.body().getMessage() : response.message())));
                }
            }

            @Override
            public void onFailure(Call<ResponseVo<Void>> call, Throwable t) {
                future.completeExceptionally(t);
            }
        });
        return future;
    }

    public CompletableFuture<ResponseVo<List<FriendRequestVo>>> getFriendRequests() {
        if (currentUserId == null) {
            CompletableFuture<ResponseVo<List<FriendRequestVo>>> future = new CompletableFuture<>();
            future.completeExceptionally(new RuntimeException("用户未登录"));
            return future;
        }

        CompletableFuture<ResponseVo<List<FriendRequestVo>>> future = new CompletableFuture<>();
        userApi.getFriendRequests(currentUserId).enqueue(new Callback<ResponseVo<List<FriendRequestVo>>>() {
            @Override
            public void onResponse(Call<ResponseVo<List<FriendRequestVo>>> call, Response<ResponseVo<List<FriendRequestVo>>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    future.complete(response.body());
                } else {
                    future.completeExceptionally(new RuntimeException("获取好友请求失败: " + 
                        (response.body() != null ? response.body().getMessage() : response.message())));
                }
            }

            @Override
            public void onFailure(Call<ResponseVo<List<FriendRequestVo>>> call, Throwable t) {
                future.completeExceptionally(t);
            }
        });
        return future;
    }

    public CompletableFuture<ResponseVo<Void>> handleFriendRequest(Long requestId, Integer status) {
        if (currentUserId == null) {
            CompletableFuture<ResponseVo<Void>> future = new CompletableFuture<>();
            future.completeExceptionally(new RuntimeException("用户未登录"));
            return future;
        }

        CompletableFuture<ResponseVo<Void>> future = new CompletableFuture<>();
        userApi.handleFriendRequest(requestId, status, currentUserId).enqueue(new Callback<ResponseVo<Void>>() {
            @Override
            public void onResponse(Call<ResponseVo<Void>> call, Response<ResponseVo<Void>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    future.complete(response.body());
                } else {
                    future.completeExceptionally(new RuntimeException("处理好友请求失败: " + 
                        (response.body() != null ? response.body().getMessage() : response.message())));
                }
            }

            @Override
            public void onFailure(Call<ResponseVo<Void>> call, Throwable t) {
                future.completeExceptionally(t);
            }
        });
        return future;
    }

    public CompletableFuture<ResponseVo<UserVo>> getCurrentUser() {
        if (currentUserId == null) {
            CompletableFuture<ResponseVo<UserVo>> future = new CompletableFuture<>();
            future.completeExceptionally(new RuntimeException("用户未登录"));
            return future;
        }

        CompletableFuture<ResponseVo<UserVo>> future = new CompletableFuture<>();
        userApi.getCurrentUser(currentUserId).enqueue(new Callback<ResponseVo<UserVo>>() {
            @Override
            public void onResponse(Call<ResponseVo<UserVo>> call, Response<ResponseVo<UserVo>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    future.complete(response.body());
                } else {
                    future.completeExceptionally(new RuntimeException("获取用户信息失败: " + 
                        (response.body() != null ? response.body().getMessage() : response.message())));
                }
            }

            @Override
            public void onFailure(Call<ResponseVo<UserVo>> call, Throwable t) {
                future.completeExceptionally(t);
            }
        });
        return future;
    }

    public Long getCurrentUserId() {
        return currentUserId;
    }

    public void setCurrentUserId(Long id) {
        this.currentUserId = id;
    }
}
